window.URL_LOGIN_PATH = "service/mmexbdlogin";
window.URL_ORDER_QUERY_PATH = "service/mmqueryncbills";
window.URL_ORDER_SUBMIT_REPORT_PATH = "service/mmbillbusiness";
window.HTTP_PROTOCOL = "http://";
window.ICMODULECODE = "IC";

$app = window.$app || {};
$Toast = $js.toast;

(function(_window,$app){
	
	var app = _window.$app || {};
	$app = _window.$app = window.$app  =  app;
	
	var deviceInfo = $device.getDeviceInfo() || {};
	var deviceInfo = typeof(deviceInfo)=='string'?$stringToJSON(deviceInfo):deviceInfo;
	$app.deviceInfo = deviceInfo;
	app.isJSONString = JSON.isJSONString;
	
	app.showToast = function(msg)
	{
		msg = msg || "";
		msg = $jsonToString(msg);
		
		$service.call('YinHeService.showToast',{msg:msg},true);
	};
	
	app.showLoadingBar = function(args)
	{		
		var msg = (args || {}).msg;
		msg = msg || "";
		msg = $jsonToString(msg);
		$service.call('YinHeService.showLoadingBar',{msg:msg},true);
	};
	
	app.hideLoadingBar = function(msg)
	{
		$service.call('YinHeService.hideLoadingBar',{},true);
	};
	
	$Toast = $js.toast = app.showToast || $js.toast;
	$js.showLoadingBar = app.showLoadingBar || $js.showLoadingBar;
	$js.hideLoadingBar = app.hideLoadingBar || $js.hideLoadingBar;
	
	app.getTableInfo = function(opt)
	{
		var option = opt || {};
		var db    = option.db;
		var table = option.table;
		if(!db)
		{
			$js.toast('数据库名不能为空！');
			return {};
		}
		if(!table)
		{
			$js.toast('表名不能为空！');
			return {};
		}
		var tableInfo = $service.call(
	        "YinHeService.getTableInfo",//服务类型
	       	{},//参数
	        "true"//是否同步，默认异步
    	) || {};
		return  tableInfo;
	};
	
	app.replaceBatch = function(info)
	{
		var that = this;
		that.replaceOrInsert('REPLACE',info);
	}
	app.insertBatch = function(info)
	{
		var that = this;
		that.replaceOrInsert('INSERT',info);
	}
	
	app.replaceOrInsert = function(command,dbInfo){
	
		var that = this;
		var info     = dbInfo || {};
		var db     	 = info.db;
		var table  	 = info.table;
		var fields 	 = info.fields;
		var values 	 = info.values;
		var callback = info.callback;
		
		var opts = {
			db:db,
			table:table,
			fields:fields,
			command:command,
			callback:callback,
			values:values
		};
		var props = Object.getOwnPropertyNames(opts);
		for(var i=0;i<props.length;i++)
		{
			var name = props[i];
			if(typeof(opts[name])=='function' && name!='callback')
			{
				$js.toast('不允许存在非法的函数！');
				return false;
			}else if(typeof(opts[name])=='function' && name=='callback'){
				var funcName = 'replaceOrInsert_callback'+'_funcID_'+Math.round(Math.random()*1000000);
				window[funcName] = callback;
				opts['callback'] = funcName+"()";
			}
		}
		var VALIED_NONULL_FIEILD = ['db','table','fields','values','command'];
		for(var i=0;i<VALIED_NONULL_FIEILD.length;i++)
		{
			var name = VALIED_NONULL_FIEILD[i];
			if(!opts.hasOwnProperty(name) || !opts[name])
			{
				$js.toast('['+name+']不允许为空！');
				return false;
			}
		}
		var dataToFile = $jsonToString(opts);
//		$alert("YinHeService.replaceOrInsert="+dataToFile);
		console.log(dataToFile);
		that.writeToFile(dataToFile,function(code,path){
			if(code==100)
			{
				 $service.call(
		        		"YinHeService.replaceOrInsert",//服务类型
			       		opts,//参数
		        		"false"//是否同步，默认异步
		  		 	);	
	  		 }else{
	  		 	console.log('YinHeService.replaceOrInsert，数据写入文件出错');
	  		 }
			
		});	
	};
	app.writeToFile = function(content,callback){
		
		if(!content)
		{
			callback(-100,null);
			return;
		}
		var path = 'sqlbatch/yinhe_data.json';
		$service.call("UMFile.delete", {
			path:path
		}, true);
		$service.call("UMFile.write", {
			content:content,
			path:path,
			charset:'UTF-8'
		}, true);
		callback(100,path);
		
	};
	
	/**
	 *检测连接可达性
	 */
	app.checkNetWorkReachable = function(host,port,callback){
		
		host = !!host &&typeof(host)=='string'?host:null;
		port = !isNaN(port)?port:-1;
		callback = (typeof(callback)=='string'||typeof(callback)=='function')?callback:null;
		
		if(typeof(callback)=='function' && !callback.name)
		{
			var funcName = 'checkNetWorkReachable_callback'+'_funcID_'+Math.round(Math.random()*1000000);
            
            while(window.hasOwnProperty(funcName))
            {
               funcName = 'checkNetWorkReachable_callback'+'_funcID_'+Math.round(Math.random()*1000000)+'_subID_'+Math.round(Math.random()*1000000);
            }
             window[funcName] = callback;
             callback = funcName +"()";
		}
		
		if(!host) {
			$js.toast('主机host不能为空！');
			return;
		}
		if(port==-1)
		{
			$js.toast('端口号不能为空！');
			return;
		}
		
   		
		$service.call(
        		"YinHeService.checkReachable",//服务类型
	       		{
	        		port:port,
	        		host:host,
	        		callback:callback
	        	},//参数
        	"false"//是否同步，默认异步
   		 );		
   		
		
	};
	/**
	 *读取网络状态 
	 */
	app.getNetworkState = function()
	{
		var state = $service.call(
        "YinHeService.getNetworkState",//服务类型
       	{},//参数
        "true"//是否同步，默认异步
    	) || {};
    	
    	if(!!state && typeof(state)=='string')
    	{
    		state = JSON.isJSONString(state)?$stringToJSON(state):{};
    	}
    	return state;
	}
	
	/**
	 *Ajax网络请求,注意，这里强制异步执行 
	 */
	app.ajax = function(options)
	{
		var args = typeof(options)=='object'?options:{};
		var params = {};
		var checkFields = ['url','type','method','tag','bindfield','header','data','timeout','callback','error'];

		Array.prototype.forEach.call(checkFields,function(item,index,arr){
			 if(!!item &&args.hasOwnProperty(item))
			 {
			 	params[item] = args[item];
			 }
		});
		checkFields = ['url','type','method','timeout','bindfield','tag'];

		Array.prototype.forEach.call(checkFields,function(item,index,arr){
			if(item=='timeout')
			{
				params[item] = (typeof(params[item])=='string' || typeof(params[item])=='number')?params[item]:'15';
			}else{
				params[item] = typeof(params[item])=='string'?params[item]:'';
			}
			
			if(item=='bindfield' &&params.hasOwnProperty(item) && !params[item])
			{
				delete params[item];
			}
		});
		params['data'] = !!params['data'] &&(typeof(params['data'])=='string'||typeof(params['data'])=='object')?params['data']:{};
		params['header'] = !!params['header'] &&(typeof(params['data'])=='object')?params['header']:{};
		
		checkFields = ['callback','error'];

		Array.prototype.forEach.call(checkFields,function(item,index,arr){
			
			if(!!params[item])
			{
				if(typeof(params[item])=='function' && !params[item].name) 
				{
						//如果是匿名函数，为了确保不发生意外，保证执行，主动给此函数命名
						var funcName = item+'_funcID_'+Math.round(Math.random()*1000000);
	                    while(window.hasOwnProperty(funcName))
	                    {
	                        funcName = item+'_funcID_'+Math.round(Math.random()*1000000)+'_subID_'+Math.round(Math.random()*1000000);
	                    }
	                    window[funcName] = params[item];
	                    params[item] = funcName+'()';				
				}
				else if(typeof(params[item])=='string')
				{
					if(params[item].indexOf(')')>params[item].indexOf('(') && params[item].indexOf('(')>0)
					{
						console.log("---continue---");
					}
					else if(params[item].indexOf(')')==params[item].indexOf(')') && params[item].indexOf(')')==-1)
					{
						params[item] = params[item] +"()";
					}else{
						delete params[item];
					}
					
				}else{
					delete params[item];
				}
			}
		});
		
		checkFields = ['url','type','method'];

		for(var i=0;i<checkFields.length;i++)
		{
			if(!params[checkFields[i]])
			{
				$js.toast('字段'+checkFields[i]+'不允许为空！');
				return;
			}
		}
		$service.call('YinHeService.sendHttp',params,"false");
	};
	
	/**
	 *  用户登录
 * @param {Object} username
 * @param {Object} password
 * @param {Object} callback
 * @param {Object} error
	 */
	$app.login = function(username,password,callback,error)
	{
		var that = this;
		var host = $cache.read('host');
		var port = $cache.read('port');
		var deviceid = $app.deviceInfo.deviceid;
		
		url = HTTP_PROTOCOL+host+':'+port+'/'+URL_LOGIN_PATH;
		
		var deviceInfo = $device.getDeviceInfo();
		var jsondevice = $stringToJSON(deviceInfo);
		var deviceuniqueid = jsondevice.deviceid;
		
		var data = {
		      "nccontext": {
		      "user": username,
		      "password": password,
		      "exsystemcode": "BarCode99",
		      "modulecode":ICMODULECODE,
		      "devicecode": 'pda001',
	          "deviceuniqueid": deviceuniqueid
	    	}
		};	
		that.ajax({
				url:url,
				type:'json',
				method:'post',
				header:{
					'Content-Type' : 'application/json;charset=utf-8'
				},
				data:data,
				timeout:20000,
				callback:callback,
				error:error,
				bindfield:'login_result'
		});
	};
	/**
	 * 检测服务器信息是否已配置 
	 */
	$app.checkServerConfig = function()
	{
		var host = ($service.readConfig('host')||'').trim();//获取Configure中key的键值
		var port = $service.readConfig('port')//获取Configure中key的键值
		return !!host && !isNaN(port)&&parseInt(port,10)>0;
	};
	
	
	//doctypes = ["55A2_QUERY","55C2_QUERY"]
	$app.loadProduceReport = function(doctype,condition,callback,error){
		console.log($stringToJSON(arguments));
		var that = this;
		var userInfo = $app.getUserInfo();
		var data = {
	    	nccontext: {
		      "user": userInfo.user,
		      "password": userInfo.pass,
		      "exsystemcode": "mmapp",
		      "devicecode": "pda001", 
		      "doctype": doctype, // "55C2_QUERY"
		      "returntype": "aggvo"
	   		 },
		    queryinfos: {
			      "totalRows": "-1",
			      "startRowNumber": "1",
			      "endRowNumber": "5000",
		    }
		};
		
		if (condition != null) {
			for (var key in condition)
			{
				if(typeof(condition[key])=='string' || typeof(condition[key])=='number')
				{
					data.queryinfos[key] = condition[key];
				}
			}
		};
		
		var host = $service.readConfig('host');//获取Configure中key的键值
		var port = $service.readConfig('port')//获取Configure中key的键值
		var url = HTTP_PROTOCOL+host+':'+port+'/'+URL_ORDER_QUERY_PATH;
		
		that.ajax({
			url:url,
			type:'json',
			method:'post',
			timeout:15000,
			data:data,
			bindfield:'load_result',
			header:{ 'Content-Type':'application/x-www-form-urlencoded;charset=utf-8'},
			callback:callback,
			error:error
		});
		
	};
	
	/**
	 *doctype ['55A2_TO_55A4':'55C2_TO_55A4' ]
	 */
	$app.submitProduceReports = function(doctype,billinfos,callback,error){
		
		console.log($jsonToString(billinfos));
		var that = this;
		var userInfo = $app.getUserInfo();
		var nccontext = {
		      "user": userInfo.user,
		      "password": userInfo.pass,
		      "exsystemcode": "mmapp",
		      "devicecode": "pda001", 
		      "doctype": doctype // "55C2_QUERY"
	   		 };
	   	var data = {
	   			nccontext:nccontext,
	   			billinfos:billinfos
	   		};
	   	var host = $service.readConfig('host');//获取Configure中key的键值
		var port = $service.readConfig('port')//获取Configure中key的键值
		var url = HTTP_PROTOCOL+host+':'+port+'/'+URL_ORDER_SUBMIT_REPORT_PATH;
		
		that.ajax({
			url:url,
			type:'json',
			method:'post',
			timeout:15000,
			data:data,
			bindfield:'load_result',
			header:{ 'Content-Type':'application/x-www-form-urlencoded;charset=utf-8'},
			callback:callback,
			error:error
		});
		
	}
	
	
	/**
	 *获取用户信息 
	 */
	$app.getUserInfo = function()
	{
		var user = $ctx.getApp('username');
		var pass = $ctx.getApp('password');
		if(!user|| !pass)
		{
			
			return {};
		}
		pass = decodeURI(atob(atob(atob(pass))));
		return {
			user:user,
			pass:pass
		};
	};
	
	$app.saveUserInfo = function(opt){
		var option = {};
		option['user'] = !!opt['user']&&typeof(opt['user'])=='string'?opt['user']:null;
		option['pass'] = !!opt['pass']&&typeof(opt['pass'])=='string'?opt['pass']:null;
		
		if(!option['user'] || !option['pass'])
		{
			return;
		}
		option['pass'] = btoa(btoa(btoa(encodeURI(option['pass']))));
		$ctx.setApp({
            "username":option['user'],
            "password":option['pass'],
        });
	};
	
})(window,$app);